package com.eedi.framework.permission.excel;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty;
import com.eedi.framework.common.exception.util.ServiceExceptionUtil;
import com.eedi.framework.permission.controller.org.vo.permission.OrgPermissionAssignUserRoleRowReq;
import com.eedi.framework.permission.enums.OrgPermissionErrorCodeConstants;

import java.util.*;
import java.util.stream.Collectors;



/**
 * excel校验器
 *
 * @Description
 * @Author wanglz
 * @Date 2024/8/2 11:05
 **/
public class ExcelListener extends AnalysisEventListener<OrgPermissionAssignUserRoleRowReq> {

    @Override
    public void invoke(OrgPermissionAssignUserRoleRowReq req, AnalysisContext context) {
        // set rowNo to data-object
        ReadRowHolder readRowHolder = context.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        req.setRowNo(rowIndex);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        if (CollUtil.isEmpty(headMap)) {
            throw ServiceExceptionUtil.exception(OrgPermissionErrorCodeConstants.COMMON_EXCEL_IMPORT_TEMPLATE_ERROR);
        }
        //获取bo对象head名称
        List<String> expectHeadList = Optional.ofNullable(context)
                .map(AnalysisContext::currentReadHolder)
                .map(ReadHolder::excelReadHeadProperty)
                .map(ExcelReadHeadProperty::getHeadMap)
                .map(Map::values)
                .orElse(Collections.emptyList())
                .stream().map(Head::getHeadNameList)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(expectHeadList)) {
            throw ServiceExceptionUtil.exception(OrgPermissionErrorCodeConstants.COMMON_EXCEL_IMPORT_TEMPLATE_ERROR);
        }
        //表头数量检测
        if (!Objects.equals(headMap.size(), expectHeadList.size())) {
            throw ServiceExceptionUtil.exception(OrgPermissionErrorCodeConstants.COMMON_EXCEL_IMPORT_TEMPLATE_ERROR);

        }
        //检查表格模板列名是否一致
        expectHeadList.forEach(x -> {
            if (!x.equalsIgnoreCase(headMap.get(expectHeadList.indexOf(x)))) {
                throw ServiceExceptionUtil.exception(OrgPermissionErrorCodeConstants.COMMON_EXCEL_IMPORT_TEMPLATE_ERROR);
            }
        });
    }
}
